package com.czy.owner.ui.order;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.StoreSelectAdapter;
import com.czy.owner.api.OwnerStoreBespokeApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.ChainStoresModel;
import com.czy.owner.entity.SelectBespokeListModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.order.frament.SelectBespokeFragment;
import com.czy.owner.ui.order.frament.SelectPackageFragment;
import com.czy.owner.ui.store.OnLineOrderActivity2;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.widget.CustomPopWindow;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static com.czy.owner.ui.store.OnLineOrderActivity2.REQUEST_DATA;

/**
 * Created by hedepu on 2017-08-25
 */

public class SelectBespokeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener {
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.tv_tab_left)
    TextView tvTabLeft;
    @BindView(R.id.tv_tab_right)
    TextView tvTabRight;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.img_popuwindow_menu)
    ImageView imgPopuwindowMenu;
    @BindView(R.id.tv_select_store)
    TextView tvSelectStore;
    @BindView(R.id.tv_distance_store)
    TextView tvDistanceStore;
    @BindView(R.id.linear_select_store)
    LinearLayout linearSelectStore;

    private String type = "0";
    private FragmentManager fragmentManager = null;
    private String[] tabTitle = new String[]{"自选项目", "已购套餐"};
    SelectBespokeFragment selectBespokeFragment;
    SelectPackageFragment selectPackageFragment;
    private boolean isClose;
    CustomPopWindow popWindow;
    private RecyclerView recyclerStore;
    private List<ChainStoresModel> mChainStoresList = new ArrayList<>();
    private StoreSelectAdapter storeSelectAdapter;
    private int storeId;
    private boolean isLocationSuccess;
    private RxPermissions rxPermissions;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    //  定位回调监听事件
    private double longItude;
    private double latItude;
    private boolean isFrist = true;
    private ChainStoresModel chainStoresModel;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_select_bespoke;
    }

    @Override
    protected void initInjector() {
        isClose = getIntent().getBooleanExtra("isClose", false);
        chainStoresModel = (ChainStoresModel) getIntent().getSerializableExtra("chainStores");
        storeId = Integer.parseInt(SharedPreferencesUtils.getParam(this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
    }

    @Override
    protected void initViews() {
        rxPermissions = new RxPermissions(this);
        if (mChainStoresList.size() == 0) {
            toolbarTitle.setText("选择预约项目");
        }
        //选择预约项目
        if (!isClose) {
            toolbarTitle.setText("选择预约项目");
            linearSelectStore.setVisibility(View.GONE);
        } else if (chainStoresModel != null) {
            toolbarTitle.setText("");
            tvSelectStore.setText(chainStoresModel.getStoreName());
            mChainStoresList.add(chainStoresModel);
        }
        if (mChainStoresList.size() == 1) {
            imgPopuwindowMenu.setVisibility(View.GONE);
        } else if (mChainStoresList.size() > 1) {
            imgPopuwindowMenu.setVisibility(View.VISIBLE);

        }
        getPermissions();

    }

    public void getPermissions() {
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initLoc();
//                            getStoreInfoData(false);

//                            PhoneUtils.ShowToastMessage(getActivity(), "获取权限成功");
                        } else {
//                            PhoneUtils.ShowToastMessage(getActivity(), "获取权限失败");


                        }
                    }
                });
    }

    //定位初始化控件配置
    private void initLoc() {
        locationClient = new AMapLocationClient(this);
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();


    }

    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {

            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    longItude = amapLocation.getLongitude();
                    latItude = amapLocation.getLatitude();
                    getStoreInfoData(isFrist, longItude, latItude);
                    MyLog.e("yang", "定位成功");
                    isFrist = false;
                } else {
                    getStoreInfoData(isFrist, 0, 0);
                    isFrist = false;
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    MyLog.e("yang", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    @Override
    protected void updateViews() {
//        getFragment(1);
//        getFragment(0);
        selectBespokeFragment = new SelectBespokeFragment();
        selectPackageFragment = new SelectPackageFragment();
//        AnotherRightFragment fragment = new AnotherRightFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.ll_main_body, selectPackageFragment);
        transaction.add(R.id.ll_main_body, selectBespokeFragment);
        if (getIntent().getIntExtra("pos", 0) == 0) {
            transaction.hide(selectPackageFragment).show(selectBespokeFragment);
            type = "0";
            tvTabLeft.setTextColor(this.getResources().getColor(R.color.appThemeColor));
            tvTabRight.setTextColor(this.getResources().getColor(R.color.appThemeSubTitleColor));
        } else {
            transaction.hide(selectBespokeFragment).show(selectPackageFragment);
            type = "1";
            tvTabLeft.setTextColor(this.getResources().getColor(R.color.appThemeSubTitleColor));
            tvTabRight.setTextColor(this.getResources().getColor(R.color.appThemeColor));
        }

        transaction.commit();
    }

    //是否第一次进入请求。。二次操作防止第一次请求失败
    private void getStoreInfoData(final boolean bool, double longItude, double latItude) {
        if (longItude == 0 & latItude == 0) {
            isLocationSuccess = false;
        } else {
            isLocationSuccess = true;
        }
        OwnerStoreBespokeApi ownerStoreInfoApi = new OwnerStoreBespokeApi(new HttpOnNextListener<List<ChainStoresModel>>() {
            @Override
            public void onNext(List<ChainStoresModel> model) {
                mChainStoresList.clear();
                mChainStoresList.addAll(model);

                if (mChainStoresList.size() == 1) {
                    imgPopuwindowMenu.setVisibility(View.GONE);
                    if (!bool)
                        PhoneUtils.ShowToastMessage(SelectBespokeActivity.this, "您绑定的门店没有分店");
                } else if (mChainStoresList.size() > 0) {
                    imgPopuwindowMenu.setVisibility(View.VISIBLE);
                    if (!bool)
                        showPoPu();
                }
                for (ChainStoresModel chainStores : mChainStoresList) {
                    if (chainStoresModel.getStoreId() == chainStores.getStoreId()) {
                        tvSelectStore.setText(chainStores.getStoreName());
                        if (isLocationSuccess && !StringUtils.isEmpty(chainStores.getMin())) {
                            tvDistanceStore.setText(chainStores.getMin() + "km");
                        }

                    }

                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                MyLog.e("yang", e.getMessage());
                PhoneUtils.ShowToastMessage(SelectBespokeActivity.this, e.getMessage());
            }

        }, this);

        ownerStoreInfoApi.setProgress(!bool);
        ownerStoreInfoApi.setStoreId(UserHelper.getInstance().getOwnerInfoModel(this).getStoreId() + "");
        ownerStoreInfoApi.setSession(UserHelper.getInstance().getSession(this));
        ownerStoreInfoApi.setGprsX(longItude + "");
        ownerStoreInfoApi.setGprsY(latItude + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerStoreInfoApi);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    private void showPoPu() {
        if (popWindow == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_select_store, (ViewGroup) this.getWindow().getDecorView(), false);
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(view)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            RotateAnimation myAnimationRotate = new RotateAnimation(180.0f, 360f,
                                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                            imgPopuwindowMenu.startAnimation(myAnimationRotate);
                            myAnimationRotate.setDuration(500);
                            myAnimationRotate.setFillAfter(true);
                        }
                    })
                    .create();
            recyclerStore = (RecyclerView) view.findViewById(R.id.recycler_store);
            storeSelectAdapter = new StoreSelectAdapter(this, mChainStoresList);
            recyclerStore.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

            recyclerStore.setLayoutManager(new LinearLayoutManager(this));
            recyclerStore.setAdapter(storeSelectAdapter);
            storeSelectAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<ChainStoresModel>() {
                @Override
                public void onItemClick(int position, ChainStoresModel model, View view) {
                    chainStoresModel = model;
                    popWindow.dissmiss();
                    tvSelectStore.setText(model.getStoreName());
                    tvDistanceStore.setText(model.getMin() + "km");
                    RxBus.getDefault().post(model);
                    selectBespokeFragment.selectStore();
                    selectPackageFragment.selectStore();

                }
            });

        }
        storeSelectAdapter.setLocSuccess(isLocationSuccess);
        storeSelectAdapter.setStoreId(Integer.parseInt(SharedPreferencesUtils.getParam(this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + ""));
        storeSelectAdapter.notifyDataSetChanged();
        popWindow.showAsDropDown(appbar, 0, PhoneUtils.dip2px(this, 10));
        RotateAnimation myAnimationRotate = new RotateAnimation(0.0f, 180.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        imgPopuwindowMenu.startAnimation(myAnimationRotate);
        myAnimationRotate.setDuration(500);
        myAnimationRotate.setFillAfter(true);

    }

    @OnClick({R.id.tv_tab_left, R.id.tv_tab_right, R.id.linear_right_img, R.id.bt_confirm, R.id.relat_select_store})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.relat_select_store:
                if (isClose) {
                    if (mChainStoresList.size() == 0) {
                        initLoc();
                    } else if (mChainStoresList.size() != 1) {
                        showPoPu();
                    }
                }
                break;
            case R.id.tv_tab_left:
                if ("0".equals(type))
                    return;
                type = "0";
                tvTabLeft.setTextColor(this.getResources().getColor(R.color.appThemeColor));
                tvTabRight.setTextColor(this.getResources().getColor(R.color.appThemeSubTitleColor));
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.hide(selectPackageFragment).show(selectBespokeFragment);
                transaction.commit();
//                getFragment(0);
                break;
            case R.id.tv_tab_right:
                if ("1".equals(type))
                    return;
                type = "1";
                tvTabLeft.setTextColor(this.getResources().getColor(R.color.appThemeSubTitleColor));
                tvTabRight.setTextColor(this.getResources().getColor(R.color.appThemeColor));
//                getFragment(1);
                FragmentManager fragmentManager2 = getSupportFragmentManager();
                FragmentTransaction transaction2 = fragmentManager2.beginTransaction();
                transaction2.hide(selectBespokeFragment).show(selectPackageFragment);
                transaction2.commit();
                break;
            case R.id.linear_right_img:

                Intent i = new Intent(this, SelectSearchBespokeActivity.class);
                i.putExtra("bespoke", (Serializable) selectBespokeFragment.getSelectedList());
                startActivityForResult(i, REQUEST_DATA);
                break;
            case R.id.bt_confirm:
                if (selectBespokeFragment.getSelectedList().size() == 0 && selectPackageFragment.getSelectList().size() == 0) {
                    PhoneUtils.ShowToastMessage(this, "你还未选择商品或服务");
                    return;
                }
                if (isClose) {
                    startActivity(new Intent(this, OnLineOrderActivity2.class).putExtra("bespoke", (Serializable) selectBespokeFragment.getSelectedList())
                            .putExtra("package", (Serializable) selectPackageFragment.getSelectList()).putExtra("packageNum", selectPackageFragment.getPackageNum()));
                    finish();
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("bespoke", (Serializable) selectBespokeFragment.getSelectedList());
                    intent.putExtra("package", (Serializable) selectPackageFragment.getSelectList());
                    intent.putExtra("packageNum", selectPackageFragment.getPackageNum());
                    setResult(REQUEST_DATA, intent);
                    finish();
                }
                break;

        }
    }


    private void getFragment(int i) {
        // getSupportFragmentManager().popBackStack()//回退调用
        fragmentManager = getSupportFragmentManager();
//        detachFragment();
        if (selectBespokeFragment == null) {
            selectBespokeFragment = new SelectBespokeFragment();
            selectPackageFragment = new SelectPackageFragment();
            attachFragment(selectBespokeFragment, tabTitle[0]);
            attachFragment(selectPackageFragment, tabTitle[1]);

        }
        detachFragment();
        if (i == 0) {
            attachFragment(selectBespokeFragment, tabTitle[i]);
        } else if (i == 1) {
            attachFragment(selectPackageFragment, tabTitle[i]);
        }
    }

    private void attachFragment(Fragment fragment, String tag) {

        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (fragment.isHidden()) {
            ft.show(fragment);
        } else if (fragment.isDetached()) {
            ft.attach(fragment);
        } else if (!fragment.isAdded()) {
            // 		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);//打开形式的动画
            //  		ft.addToBackStack(null);//添加进栈中
            ft.add(R.id.ll_main_body, fragment, tag);
        }
        ft.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_DATA && resultCode == REQUEST_DATA && selectPackageFragment != null) {
            if (data.getSerializableExtra("bespoke") != null) {
                selectBespokeFragment.setSelectedData((List<SelectBespokeListModel>) data.getSerializableExtra("bespoke"));
            }

        }
    }

    /**
     * 隐藏当前Fragment
     */
    private void detachFragment() {

        for (int i = 0; i < tabTitle.length; i++) {
            Fragment fragment = fragmentManager.findFragmentByTag(tabTitle[i]);
            if (fragment != null && !fragment.isDetached()) {
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.hide(fragment);
                ft.commit();
            }
        }
    }
}
